package com.ruoyi.operation.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.alibaba.excel.EasyExcel;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.excel.utils.ExcelUtil;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.mybatis.core.page.PageQuery;
import com.ruoyi.operation.domain.vo.ResTableVo;
import lombok.RequiredArgsConstructor;
import org.dromara.warm.flow.core.enums.FlowStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.operation.domain.vo.TSqltoolVo;
import com.ruoyi.operation.domain.bo.TSqltoolBo;
import com.ruoyi.operation.service.ITSqltoolService;
import com.ruoyi.common.mybatis.core.page.TableDataInfo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.servlet.http.HttpServletResponse;

/**
 * sql执行工具控制器
 * 前端访问路由地址为:/operation/sqltool
 *
 * @author ruoyi
 * @date 2025-06-18
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/sqltool")
public class TSqltoolController extends BaseController {

    private final ITSqltoolService iTSqltoolService;

    /**
     * 查询sql执行工具列表
     */
    @SaCheckPermission("operation:sqltool:list")
    @GetMapping("/list")
    public TableDataInfo<TSqltoolVo> list(TSqltoolBo bo, PageQuery pageQuery) {
        return iTSqltoolService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出sql执行工具列表
     */
    @SaCheckPermission("operation:sqltool:export")
    @Log(title = "sql执行工具", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(TSqltoolBo bo, HttpServletResponse response) {
        List<TSqltoolVo> list = iTSqltoolService.queryList(bo);
        ExcelUtil.exportExcel(list, "sql执行工具", TSqltoolVo.class, response);
    }

    /**
     * 获取sql执行工具详细信息
     * @param id 主键
     */
    @SaCheckPermission("operation:sqltool:query")
    @GetMapping("/{id}")
    public R<TSqltoolVo> getInfo(@NotNull(message = "主键不能为空") @PathVariable String id) {
        return R.ok(iTSqltoolService.queryById(id));
    }

    /**
     * 新增sql执行工具
     */
    @SaCheckPermission("operation:sqltool:add")
    @Log(title = "sql执行工具", businessType = BusinessType.INSERT)
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody TSqltoolBo bo) {
        return toAjax(iTSqltoolService.insertByBo(bo));
    }

    /**
     * 修改sql执行工具
     */
    @SaCheckPermission("operation:sqltool:edit")
    @Log(title = "sql执行工具", businessType = BusinessType.UPDATE)
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody TSqltoolBo bo) {
        return toAjax(iTSqltoolService.updateByBo(bo));
    }

    /**
     * 删除sql执行工具
     *
     * @param ids 主键串
     */
    @SaCheckPermission("operation:sqltool:remove")
    @Log(title = "sql执行工具", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空") @PathVariable String[] ids) {
        return toAjax(iTSqltoolService.deleteWithValidByIds(Arrays.asList(ids), true));
    }

    @SaCheckPermission("operation:sqltool:execute")
    @Log(title = "sql执行工具", businessType = BusinessType.OTHER)
    @GetMapping("/execute/sql")
    public R<ResTableVo> executeSql(@RequestParam String name) {
        return R.ok(iTSqltoolService.queryConfigSql(name));
    }

    @SaCheckPermission("operation:sqltool:execute")
    @GetMapping("/remote/dburl")
    public R<List<String>> remoteUrl(@RequestParam String dbType){
        return R.ok(iTSqltoolService.remoteUrl(dbType));
    }


    @PostMapping("/result/export")
    @Log(title = "sql结果导出", businessType = BusinessType.EXPORT)
    public void exportSql(TSqltoolBo bo,HttpServletResponse response) {
        try {
            ResTableVo resTableVo = iTSqltoolService.queryConfigSql(bo.getToolname());
            List<List<String>> header = resTableVo.getTableHeader().stream().map(x -> {
                List<String> list = new ArrayList<>();
                list.add(x);
                return list;
            }).collect(Collectors.toList());
            List<Map<String, Object>> tableData = resTableVo.getTableData();
            List<Object> result = tableData.stream().map(x -> x.values().stream().collect(Collectors.toList())).collect(Collectors.toList());
            EasyExcel.write(response.getOutputStream())
                .head(header).sheet()
                .doWrite(result);
        } catch (IOException e) {
            throw new RuntimeException("导出结果异常");
        }
    }
}
